package com.qyhl.module_activities.act.detail;

import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.core.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;

import com.qyhl.module_activities.R;
import com.qyhl.module_activities.act.album.ActAlbumFragment;
import com.qyhl.module_activities.act.comment.CommentListFragment;
import com.qyhl.module_activities.act.player.list.PlayerListFragment;
import com.qyhl.module_activities.act.player.newlist.PlayerNewListFragment;
import com.qyhl.module_activities.common.ActivityConstant;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.commonlib.entity.act.ActDetailsBean;
import com.qyhl.webtv.commonlib.entity.act.ActivityBean;
import com.qyhl.webtv.commonlib.entity.act.ActivityImageBean;
import com.qyhl.webtv.commonlib.entity.act.ActivityListTempBean;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

public class ActNewDetailsPresenter implements ActNewDetailsContract.ActDetailsPresenter {
    private ActNewDetailsContract.ActDetailsModel model;
    private ActNewDetailsContract.ActDetailsView view;

    private PlayerNewListFragment playerNewListFragment;

    public ActNewDetailsPresenter(ActNewDetailsContract.ActDetailsView view) {
        model = new ActNewDetailsModel(this);
        this.view = view;
    }


    @Override
    public void onError(int i, String s) {
        view.onError(i, s);
    }

    @Override
    public void onSuccess(ActDetailsBean data) {
        correctData(data);
        parseDate(data.getActivity());
        view.onSuccess(data, getSpannableString(data.getActivity()), getNavigation(data));
    }

    private void correctData(ActDetailsBean data) {
        correct(data);
        correct(data.getActivityLive());
        correct(data.getActivity());
        correct(data.getActivity().getActivity());
        correct(data.getActivity().getImages());
        correct(data.getActivity().getVote());
    }

    private void correct(Object data) {
        if (data != null) {
            try {
                Field[] fields = data.getClass().getDeclaredFields();
                if (fields != null) {
                    for (Field field : fields) {
                        field.setAccessible(true);
                        if (field.get(data) == null) {
                            if (field.getType().getSimpleName().equals(Integer.class.getSimpleName())) {
                                field.set(data, 0);
                            }
                            if (field.getType().getSimpleName().equals(Long.class.getSimpleName())) {
                                field.set(data, 0L);
                            }
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void getData(int actId, int type) {
        model.getActDetails(actId, type);
    }

    @Override
    public void checkSign(Integer id) {
        model.checkSign(id + "");
    }

    @Override
    public void checkError(int code) {
        view.checkError(code);
    }

    @Override
    public void checkSuccess() {
        view.checkSuccess();
    }

    @Override
    public void colleciton(int actId, String s) {
        model.colleciton(String.valueOf(actId), s);
    }

    @Override
    public void collecitonError(String msg) {
        view.collecitonError(msg);
    }

    @Override
    public void collecitonSuccess() {
        view.collecitonSuccess();
    }

    /**
     * 活动状态
     *
     * @param activityListTempBean
     */
    private SpannableStringBuilder getSpannableString(ActivityListTempBean activityListTempBean) {
        //活动状态
        int actStatus = activityListTempBean.getActStatus();
        //选手状态
        int applyStatus = activityListTempBean.getApplyStatus();
        //投票状态
        int voteStatus = activityListTempBean.getVoteStatus();

        SpanUtils spanUtils = new SpanUtils((Context) view);
        if (actStatus == ActivityConstant.STATUS_PROCESSING) {
            if (applyStatus == ActivityConstant.SING_UP_ON) {
                //报名中
                spanUtils.appendImage(ContextCompat.getDrawable((Context) view, R.drawable.img_status_singup));
            } else if (voteStatus == ActivityConstant.VOTE_ON) {
                //投票中
                spanUtils.appendImage(ContextCompat.getDrawable((Context) view, R.drawable.img_status_voteon));
            } else {
                //进行中
                spanUtils.appendImage(ContextCompat.getDrawable((Context) view, R.drawable.img_status_processing));
            }
        } else if (actStatus == ActivityConstant.STATUS_END) {
            //已结束
            spanUtils.appendImage(ContextCompat.getDrawable((Context) view, R.drawable.img_status_end));
        }
        spanUtils.append(activityListTempBean.getActivity().getActName().trim());
        return spanUtils.create();
    }

    /**
     * 时间转换
     */
    private void parseDate(ActivityListTempBean bean) {
        SimpleDateFormat sdfparse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        SimpleDateFormat sdfformat = new SimpleDateFormat("MM.dd HH:mm", Locale.US);
        bean.getActivity().setStartTime(getTime(sdfformat, sdfparse, bean.getActivity().getStartTime()));
        bean.getActivity().setEndTime(getTime(sdfformat, sdfparse, bean.getActivity().getEndTime()));
        bean.getActivity().setApplyEndTime(getTime(sdfformat, sdfparse, bean.getActivity().getApplyEndTime()));
        if (bean.getVote() != null) {
            bean.getVote().setEndTime(getTime(sdfformat, sdfparse, bean.getVote().getEndTime()));
            bean.getVote().setStartTime(getTime(sdfformat, sdfparse, bean.getVote().getStartTime()));
        }
    }

    private String getTime(SimpleDateFormat sdfformat, SimpleDateFormat sdfparse, String data) {
        String time;
        if (TextUtils.isEmpty(data)) {
            time = "-";
        } else {
            try {
                time = sdfformat.format(sdfparse.parse(data));
            } catch (ParseException e) {
                time = data;
                e.printStackTrace();
            }
        }
        return time;
    }

    private ViewPageAdapter getNavigation(ActDetailsBean actDetailsBean) {
        ActivityBean activityBean = actDetailsBean.getActivity().getActivity();
        ArrayList<Fragment> list = new ArrayList<>();
        ArrayList<String> names = new ArrayList<>();
        if (activityBean.getIsVote() == 1) {
            names.add("活动投票");
            //判断是否是新的投票
            if (actDetailsBean.getVote() != null && actDetailsBean.getVote().getExtraRule() == 1) {
                list.add(playerNewListFragment = PlayerNewListFragment.newInstance(activityBean.getId(),
                        activityBean.getPageViews(), actDetailsBean.getSumPlayer(),
                        actDetailsBean.getSumVote(),
                        actDetailsBean.getVote().getVoteNum(),
                        actDetailsBean.getVote().getPerMinVote(),
                        actDetailsBean.getVote().getPerReceiver()));
            } else {
                list.add(PlayerListFragment.newInstance(activityBean.getId(),
                        activityBean.getPageViews(), actDetailsBean.getSumPlayer(),
                        actDetailsBean.getSumVote(),
                        actDetailsBean.getActivity().getVoteStatus(),
                        actDetailsBean.getActivity().getActStatus()));
            }
        }
        names.add("活动介绍");
        list.add(ActivityDetailsFragment.newInstance(activityBean.getDetail()));
        if (activityBean.getIsAlbum() == 1) {
            names.add("活动相册");
            list.add(ActAlbumFragment.newInstance((ArrayList<ActivityImageBean>) actDetailsBean.getImages(), activityBean.getId()));
        }
        if (activityBean.getIsComment() == 1) {
            names.add("活动评论");
            list.add(CommentListFragment.newInstance(activityBean.getId()));
        }
        if (!TextUtils.isEmpty(activityBean.getResult()) && activityBean.getShowResult() == 1) {
            names.add("结果公布");
            list.add(ActivityDetailsFragment.newInstance(activityBean.getResult()));
        }
        return new ViewPageAdapter(((FragmentActivity) view).getSupportFragmentManager(), list, names.toArray(new String[1]));
    }

    class ViewPageAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragmentList;
        private String[] names;

        public ViewPageAdapter(FragmentManager fm, ArrayList<Fragment> fragmentList, String[] names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        PlayerNewListFragment getPlayerFragment() {
            if (fragmentList.get(0) instanceof PlayerNewListFragment) {
                return playerNewListFragment;
            } else {
                return null;
            }
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names[position];
        }

        int getPlayerListPosition() {
            int pos = 0;
            for (int i = 0; i < names.length; i++) {
                if (names[i].equals("活动投票")) {
                    pos = i;
                    break;
                }
            }
            return pos;
        }

        public int getCommentPosition() {
            int pos = 0;
            for (int i = 0; i < names.length; i++) {
                if (names[i].equals("活动评论")) {
                    pos = i;
                    break;
                }
            }
            return pos;
        }
    }
}
